package com.yc.web.fillter;

import com.yc.bean.Resuser;
import com.yc.commons.RedisHelper;
import com.yc.utils.YcConstants;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.rmi.server.UID;

/**
 * @author zwei
 * @create 2024-06-18 18:44
 */
@WebFilter(value = "/user.action")
public class DeviceFilter extends BaseFilter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //前置增强
        filterChain.doFilter(request,response); //过滤器向后调用
        //后置增强
        //只针对  login操作的响应上做处理  判断是否登录成功
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        String op=req.getParameter("op");
        if ("login".equals(op)){
            //说明是login操作
            //如果登录成功  在session中一定有 resuser
            HttpSession session=req.getSession();
            if (session.getAttribute(YcConstants.RESUSER)!=null){
                Resuser resuser= (Resuser) session.getAttribute(YcConstants.RESUSER);
                String userid= resuser.getUserid()+"";
                //取出request中记录的所有设备信息
                Browser browser= UserAgent.parseUserAgentString(req.getHeader("User-Agent")).getBrowser();
                String browserName=browser.getName();
                Jedis jedis= RedisHelper.getRedisInstance();
                //存入设备中使用过的用户
                jedis.sadd(browserName+YcConstants.REDIS_DEVICE_USERS, userid);
                //存入用户使用过的设备
                jedis.lpush(userid+YcConstants.REDIS_USER_DEVICE,browserName);
                jedis.close();
            }
        }
    }

    @Override
    public void destroy() {

    }
}
